package com.second.app.thread.wait.p_c;

import com.second.app.thread.p_c_test.ValueObject;

/**
 * @Author GYZ
 * <pre>
 *    生产消费模式 设置值或者获取值
 * </pre>
 */
public class ProduceConsumeDemo {

    private final String lock;

    public ProduceConsumeDemo(String lock) {
        this.lock = lock;
    }

    public void setValue() {
        try {
            synchronized (lock) {
                if (!ValueObject.getValue().equals("")) {
                    //不为空，则不生产
                    lock.wait();
                }
                String value = System.currentTimeMillis() + "_" + System.nanoTime();
                System.out.println("线程"+Thread.currentThread().getName()+",set的值是 " + value);
                ValueObject.setValue(value);
                lock.notify();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    public void getValue() {
        try {
            synchronized (lock) {
                if (ValueObject.getValue().equals("")) {
                    lock.wait();
                }
                System.out.println("线程"+Thread.currentThread().getName()+",get的值是 " + ValueObject.getValue());
                ValueObject.setValue("");
                lock.notify();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

